package br.com.pontoclass.primes;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import br.com.pontoclass.google.exception.SpreadSheetNotCreatedException;

import com.google.common.io.ByteStreams;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetQuery;
import com.google.gdata.data.Category;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaByteArraySource;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;


public abstract class GoogleSpreadsheetUtil {

    public static SpreadsheetEntry buildSpreadsheetEntry(GoogleService service, String spreadSheet, String spreadsheetGoogleURL, String spreadsheetGoogleURLForCreation, String userName, String applicationId) throws SpreadSheetNotCreatedException {
        FeedURLFactory factory = FeedURLFactory.getDefault();
        SpreadsheetQuery query = null;
        try {
            query = new SpreadsheetQuery(new URL(spreadsheetGoogleURL));
        } catch (MalformedURLException e) {
            query = new SpreadsheetQuery(factory.getSpreadsheetsFeedUrl());
        }
        query.setTitleExact(true);
        query.setTitleQuery(spreadSheet);
        SpreadsheetEntry entry = null;
        try {
            SpreadsheetFeed feed = service.query(query, SpreadsheetFeed.class);
            List<SpreadsheetEntry> entries = feed.getEntries();
            if(entries != null && entries.size() > 0) {
                entry = entries.get(0);
            } else {
                service.useSsl();
                entry = new SpreadsheetEntry();
                entry.setTitle(new PlainTextConstruct(spreadSheet));
                URL feedUrl= new URL(String.format("%s?title=%s&xoauth_requestor_id=%s", spreadsheetGoogleURLForCreation,
                                                   URLEncoder.encode(spreadSheet, "UTF-8"), 
                                                   URLEncoder.encode(userName, "UTF-8")));
                SpreadsheetFeed resultFeed = service.getFeed(feedUrl, SpreadsheetFeed.class);
                if(resultFeed != null) {
                    entry = resultFeed.createEntry();
                    Category categ = new Category("primes");
                    categ.setScheme("http://schemas.google.com/g/2005#kind");
                    categ.setLabel("spreadsheet");
                    categ.setTerm("http://schemas.google.com/docs/2007#spreadsheet");
                    entry.getCategories().add(categ);
                    MediaContent cont = new MediaContent();
                    cont.setMediaSource(new MediaByteArraySource(
                         ByteStreams.toByteArray(Thread.currentThread()
                                                       .getContextClassLoader()
                                                       .getResourceAsStream("empty.xls")), 
                                                 "application/xls"));
                    entry.setContent(cont);
                    entry.setTitle(new PlainTextConstruct(spreadSheet));
                    entry = service.insert(feedUrl, entry);
                    feed = service.query(query, SpreadsheetFeed.class);
                    entries = feed.getEntries();
                    if(entries != null && entries.size() > 0) {
                        entry = entries.get(0);
                    }
                } else {
                    throw new SpreadSheetNotCreatedException(String.format("It was not possible to create the spreadsheet '%s', unknown google behaviour.", spreadSheet));
                }
            }
        } catch (IOException | ServiceException e) {
            throw new SpreadSheetNotCreatedException(e);
        }
        if(entry == null) {
            throw new SpreadSheetNotCreatedException(String.format("It was not possible to create the spreadsheet '%s', SpreadsheetEntry was null.", spreadSheet));
        }
        return entry;
    }
}